from django.db import models
from django.contrib.auth.models import User
# from ckeditor.fields import TextField
# from ckeditor_uploader.fields import  TextField
from my_ali.settings import MEDIA_URL

# Create your models here.


class InformationClassification(models.Model):
    """资讯分类"""
    info_name_en = models.CharField(max_length=128, verbose_name="资讯分类en")
    info_name_cn = models.CharField(max_length=128, verbose_name="资讯分类cn")

    def __str__(self):
        return self.info_name_cn

    class Meta:
        verbose_name = "资讯分类"
        verbose_name_plural = verbose_name


class Tag(models.Model):
    """标签"""
    tag_name_en = models.CharField(max_length=128, verbose_name="标签en")
    tag_name_cn = models.CharField(max_length=128, verbose_name="标签cn")

    def __str__(self):
        return self.tag_name_cn

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = verbose_name


class Topic(models.Model):
    """专题活动"""
    topic_title = models.CharField(max_length=128, verbose_name="专题标题")
    topic_cover = models.ImageField(upload_to='./business_eval/%Y/%m%d/', verbose_name='专题封面')
    topic_tag = models.ForeignKey(Tag, verbose_name="关联Tag")
    topic_enable = models.BooleanField(default=True, verbose_name="是否启用")

    def __str__(self):
        return self.topic_title

    class Meta:
        verbose_name = "专题活动"
        verbose_name_plural = verbose_name


class LinkCategory(models.Model):
    """链接分类"""
    link_category_name_en = models.CharField(max_length=128, verbose_name="链接分类en")
    link_category_name_cn = models.CharField(max_length=128, verbose_name="链接分类cn")

    def __str__(self):
        return self.link_category_name_cn

    class Meta:
        verbose_name = "链接分类"
        verbose_name_plural = verbose_name


class Links(models.Model):
    """链接"""
    link_name = models.CharField(max_length=128, verbose_name='链接名')
    link_url = models.CharField(max_length=256, verbose_name="链接地址")
    link_category = models.ForeignKey(LinkCategory, verbose_name="链接分类")
    link_parent = models.ForeignKey('self', verbose_name='上级标题', null=True, blank=True, default=None)

    def __str__(self):
        return self.link_name

    class Meta:
        verbose_name = "链接"
        verbose_name_plural = verbose_name


class Article(models.Model):
    """文章信息"""
    article_title = models.CharField(max_length=128, verbose_name='文章标题')
    article_cover = models.ImageField(upload_to='./article/%Y/%m%d/', verbose_name='文章封面',
                                      default='./article/article_default.jpg')
    article_information_classification = models.ForeignKey(InformationClassification, verbose_name="资讯分类")
    article_tag = models.ManyToManyField(Tag, verbose_name="标签", related_name='article_set') # related_name : modelname_set
    article_abstract = models.CharField(max_length=128, verbose_name='文章摘要')
    article_content = models.TextField(verbose_name="文章详情")
    publish_date = models.DateTimeField(auto_now_add=True)
    view_times = models.IntegerField(default=0, verbose_name="浏览次数")
    is_notice = models.BooleanField(default=False, verbose_name="开启公告", help_text="如果为True, 在首页公告显示")
    is_case = models.BooleanField(default=False, verbose_name="经典案例")
    is_business_evaluation = models.BooleanField(default=False, verbose_name="阿里商评")
    is_recommend = models.BooleanField(default=False, verbose_name="小研推荐")

    def __str__(self):
        return self.article_title

    def save(self, *args, **kwargs):
        """
        如果文章封面没有上传，则
        1. 正文中有本地图片，使用正文中第一个图片替换
        2. 正文中没有本地图片，使用默认图片
        """
        import re
        import os
        print('1111', type(self.article_cover), self.article_cover.url)
        if self.article_cover.url == os.path.join(MEDIA_URL, 'article/article_default.jpg'):
            print(self.article_content)
            first_img_search = re.search(MEDIA_URL+r'([\w\d\-_\./]+\.(png|jpg|gif|jpeg))\b', self.article_content)
            if first_img_search:
                self.article_cover = first_img_search.groups()[0]
            # else:
            #     first_img_search = re.search(r'<img.*?src="(.*?(png|jpg|jpeg|gif))"', self.article_content)
            #     if first_img_search:
            #         self.article_cover = first_img_search.groups()[0]
        return super().save(*args, **kwargs)

    class Meta:
        verbose_name = "文章表"
        verbose_name_plural = verbose_name
        ordering = ["-publish_date"]


class Report(models.Model):
    """报告图书"""
    report_title = models.CharField(max_length=128, verbose_name="报告标题")
    article = models.ForeignKey(Article, verbose_name="相关文章链接", null=True, blank=True)
    report_cover = models.ImageField(upload_to='./report/%Y/%m%d/', verbose_name='报告封面')
    report_publisher = models.CharField(max_length=128, verbose_name="发布方")
    is_recommend = models.BooleanField(default=False, verbose_name="是否推荐")
    report_enable = models.BooleanField(default=True, verbose_name="是否启用")

    def __str__(self):
        return self.report_title

    class Meta:
        verbose_name = "报告图书"
        verbose_name_plural = verbose_name
        ordering = ['-id']


class Option(models.Model):
    """专家观点"""
    option_title = models.CharField(max_length=256, verbose_name="观点标题")
    option_abstract = models.CharField(max_length=512, verbose_name="观点摘要")
    article = models.ForeignKey(Article, verbose_name="相关文章链接")
    option_cover = models.ImageField(upload_to='./option/%Y/%m%d/', verbose_name='专家封面')
    option_name = models.CharField(max_length=64, verbose_name="专家名字")

    def __str__(self):
        return self.option_title

    class Meta:
        verbose_name = "专家观点"
        verbose_name_plural = verbose_name


class TopArticle(models.Model):
    """首页置顶"""
    top_article_title = models.CharField(max_length=256, verbose_name="文章标题")
    top_article_abstract = models.CharField(max_length=512, verbose_name="文章摘要")
    article = models.ForeignKey(Article, verbose_name="相关文章链接")
    top_article_cover = models.ImageField(upload_to='./toparticle/%Y/%m%d/', verbose_name='文章封面')
    tag = models.ForeignKey(Tag, verbose_name="相关标签")

    def __str__(self):
        return self.top_article_title

    class Meta:
        verbose_name = "首页置顶"
        verbose_name_plural = verbose_name
        ordering = ['-id']


class Banner(models.Model):
    """首页Banner"""
    banner_title = models.CharField(max_length=128, verbose_name='Banner标题')
    banner_cover = models.ImageField(upload_to='./banner/%Y/%m%d/', verbose_name='Banner图')
    banner_desc = models.TextField(verbose_name='Banner描述')
    tag = models.ForeignKey(Tag, null=True, blank=True)
    banner_link = models.CharField(max_length=256, verbose_name='Banner链接', null=True, blank=True)
    banner_enable = models.BooleanField(default=True, verbose_name="是否启用")

    def __str__(self):
        return self.banner_title

    class Meta:
        verbose_name = "首页Banner"
        verbose_name_plural = verbose_name


class Guid(models.Model):
    """导航信息"""
    guid_name = models.CharField(max_length=128, verbose_name="导航名")
    tag = models.ForeignKey(Tag, verbose_name="相关tag")
    guid_enable = models.BooleanField(default=True, verbose_name="是否启用")

    class Meta:
        verbose_name = "导航信息"
        verbose_name_plural = verbose_name

